import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Tree,
  Switch,
  Progress, DatePicker, Badge, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import find from 'lodash/find';
import Loading from '@/components/Loading';
import debounce from 'lodash/debounce';
import Detail from './../Meters/Detail';
import ReactDataGrid from 'react-data-grid';
import request from '@/utils/request';
import {afterCloseModal, renderValveOpen} from '@/utils/utils';
import BuildModalTitle from "@/components/BuildModalTitle";
import Setting from "./setting";
const FormItem = Form.Item;
const Option = Select.Option;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ meter_warm, loading,global }) => ({
  meter_warm,
  global,
  loading: loading.models.meter_warm,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      all_vendors: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      meter_warm: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        meter_warm: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'meter_warm/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'meter_warm/changeLoaded',
          });
          dispatch({
            type: 'meter_warm/changeTableY',
          });


        },
      });
    }

    const that = this;
    request(`/all_vendors`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_vendors: response.data.data,
        });
      }

    });

    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'meter_warm/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'meter_warm/changeTableY',
    });
  };

  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'meter_warm/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
        const {
          meter_warm: { scrollData },
        } = that.props;
        const table = document.querySelector('.react-grid-Canvas');
        if(table){
          setTimeout(() => {
            table.scrollTop = 0;
            table.scrollLeft = scrollData.x;
          }, 0);
        }

      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      meter_warm: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label={'日期'}>
          {getFieldDecorator('date', {
            initialValue: moment(searchParams.date),
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
      {/*  <FormItem label="水表厂商">
          {getFieldDecorator('vendor_id', {
            initialValue: searchParams.vendor_id,
          })(
            <Select style={{ width: '100px' }} allowClear>
              {
                this.state.all_vendors.map((item, index) => {
                  return <Option key={index} value={item.id}>{item.name}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>*/}
        <FormItem label="水表号">
          {getFieldDecorator('meter_number', {
            initialValue: searchParams.meter_number,
          })(<Input style={{ width: '100px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="地址">
          {getFieldDecorator('address', {
            initialValue: searchParams.address,
          })(<Input style={{ width: '100px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
       {/*  <FormItem label="尺寸类型">
          {getFieldDecorator('size_type', {
            initialValue: searchParams.size_type,
          })(
            <Select style={{ width: '120px' }} allowClear >
              <Option value={''}>全部</Option>
              <Option value={'2'}>大表</Option>
              <Option value={'1'}>小表</Option>
            </Select>,
          )}
        </FormItem> */}
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                  date: moment(fieldsValue.date).format('YYYY-MM-DD'),
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }
  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const {
        meter_warm: { searchParams },
      } = this.props;
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.handleSearch({
          page: 1,
          per_page: searchParams.per_page,
          ...fieldsValue,
          date: moment(fieldsValue.date).format('YYYY-MM-DD'),
        });

      });
    }
  }
  handleSetting=()=>{
    let company_id=sessionStorage.getItem('company_id');
    const formValues = this.imeiForm.props.form.getFieldsValue();
    const that = this;
    request(`/configs`,{
      method:'PUT',
      data:{
        "config": {
          ...formValues,
        },
        "company_id": company_id,

        region_id:localStorage.getItem('area_id')?localStorage.getItem('area_id'):'6901726763131338752',
      }
    }).then((response)=>{
      if(response.status===200){
        message.success('修改报警设置成功');
        that.setState({
          settingModal: false,
        });
        const {
          meter_warm: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }
    });
  }
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      date:moment().subtract(1, "day").format("YYYY-MM-DD"),
      meter_number:'',
      online_status:'0',
      abnormal_days:'',
      user_number:'',
      vendor_id:'',
      address:'',
      size_type:'',
      status:'0',
      page: 1,
      per_page: 50,
    });
  };

  renderValueStatus=(val)=>{
    let status='success';
    let explain='';
    switch (val){
      case -4:
        status='error'
        explain= '错报'
        break;
      case -3:
        status='error'
        explain='抄表失败'
        break;
      case -2:
        status='warning'
        explain= '漏报'
        break;
      case -1:
        status='warning'
        explain= '未上报'
        break;
      default:
        status='success'
        explain= '正常'
    }
    return (
      <p>
        <Badge status={status}/>{explain}
      </p>
    )
  }
  render() {
    const that = this;
    const {
      meter_warm: { data, loading, tableY, meta, searchParams, selectedRowKeys, status_count, total_consumption},
      global:{gridTableW}
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        frozen:true,
        key: '_index',
        formatter: (event) => {
          const {
            meter_warm: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '水表号',
        frozen:true,
        width: 140,
        key: 'meter_number',
      },
      {
        name: '安装地址',
        frozen:true,
        key: 'address',
        width: 200,
      },
      {
        name: '用水量',
        key: 'consumption',
        width: 80,
      },
      {
        name: '用水量报警值',
        key: 'consumption_abnormality_value',
        width: 100,
      },
      {
        name: '水表读数(m3)',
        key: 'value',
        width: 100,
      },
      {
        name: '上传时间',
        key: 'upload_time',
        width: 170,
      },
      {
        name: '操作',
        width: 100,
        key: 'right',
        classname:'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            size="small"
            icon="eye"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                infoModal: true,
              });
            }
            }
          >详情
          </Button>
        </Fragment>,
      },
    ].map(c => ({  ...defaultColumnProperties,...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if(totalWidth<gridTableW){
      columns[columns.length-1].width=   columns[columns.length-1].width+gridTableW-totalWidth
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>水表用水量报警</span>
      </div>
      <div className="table-page table-page-flex">
        <div className="table-page-right">
          <div className="table-info">
            <div className="table-info-item  animated fadeInLeft">
              <p className={'error'}>水表报警数量(个)</p>
              <h4 className={'error'}>{meta.total}</h4>
            </div>

            <div size="large" className="table-info-right-item  animated fadeInRight">

            </div>
          </div>
          <div className="table-condition">{this.renderSimpleForm()}</div>
          <div  className={'table-data-content'}>
            <ReactDataGrid
              columns={columns}
              rowGetter={i => {
                return { ...data[i], _index: i };
              }}
              rowsCount={data.length}
              minHeight={tableY}
              rowSelection={{
                showCheckbox: false,
                enableShiftSelect: true,
                selectBy: {
                  indexes: selectedRowKeys,
                },
              }}
              onRowClick={
                (index,row) => {
                  console.log('row',row)
                  if(!row){
                    return
                  }
                  this.props.dispatch({
                    type: 'meter_warm/changeSelectRow',
                    payload: {
                      selectedIndex:[index],
                      row:row
                    },
                  });
                }
              }

            />
            {
              loading&&<Loading />
            }
          </div>
        </div>



      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }}
                      resetScrollY={() => {
                        console.log('resetScrollY');


                      }}
                      meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Drawer
        title={`${this.state.editRecord.meter_number} 详情`}
        placement="right"
        destroyOnClose
        closable={false}
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}
        width={800}
        visible={this.state.infoModal}
      >
        <Detail  id={this.state.editRecord.meter_id}></Detail>
      </Drawer>
      <Modal
        title={<BuildModalTitle visible={this.state.settingModal} modalClass="settingModal"
                                title={`报警设置`}/>}
        destroyOnClose
        visible={this.state.settingModal}
        centered
        onOk={this.handleSetting}
        className="settingModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ settingModal: false, editRecord: {} });
        }}

      >
        <Setting editRecord={this.state.editRecord}
                  wrappedComponentRef={(inst) => this.imeiForm = inst}/>
      </Modal>
    </div>;
  }
}

export default BasicList;
